package com.shekhar.paas.web;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.shekhar.paas.domain.Story;
import com.shekhar.paas.story.StoryService;

@RequestMapping("/")
@Controller
public class HomeController {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    StoryService storyService;

    /**
     * A user should be able to see top 10 stories of last 24 hours if ten
     * stories are not found then user should see top ten stories in last two
     * days.
     * 
     * @return user should be redirected to home page
     * 
     */
    @RequestMapping(produces = "text/html", method = RequestMethod.GET)
    public ModelAndView showTopTenStories() {
        logger.info("Fetching top ten stories for today....");
        ModelAndView modelAndView = new ModelAndView();
        List<Story> topTenStories = storyService.findCurrentTopTenStories();
        if (CollectionUtils.isEmpty(topTenStories) || topTenStories.size() < 10) {
            topTenStories = storyService.fetchTopTenForLast24Hours();
        }
        logger.info("Stories found : " + topTenStories);
        if(!CollectionUtils.isEmpty(topTenStories)){
            logger.info("Stories found : " + topTenStories.size());
        }
        modelAndView.addObject("topTenStories", topTenStories);
        modelAndView.setViewName("index");
        return modelAndView;
    }

}
